package tzhomestudio.framework.implementation.config_service;

import org.apache.commons.cli.*;
import tzhomestudio.framework.interfaces.config_service.CmdLineOption;
import tzhomestudio.framework.interfaces.config_service.ICmdLine;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Timur Zolotuhin (tzolotuhin@parallels.com)
 */
public class CliCmdLine implements ICmdLine {
    // Main data
    private List<CmdLineOption> cmdLineOptions;
    private Options options;

    // Mutex
    private final Object generalMutex = new Object();

    public CliCmdLine() {
        cmdLineOptions = new ArrayList<>();
        options = new Options();
    }

    @Override
    public void addOption(CmdLineOption option) {
        synchronized (generalMutex) {
            cmdLineOptions.add(option);
            options.addOption(option);
            new Options();
        }
    }

    @Override
    public void parseCmdLineArgs(String[] args) throws ParseException {
        synchronized (generalMutex) {
            CommandLineParser parser = new BasicParser();
            CommandLine cmdLine = parser.parse(options, args);

            // synchronize options
            for (CmdLineOption option : cmdLineOptions) {
                String optName = option.getOpt();
                if (optName == null)
                    optName = option.getLongOpt();

                if (cmdLine.hasOption(optName)) {
                    option.setValues(cmdLine.getOptionValues(optName));
                } else {
                    option.setValues(option.getDefaultValues());
                }
            }
        }
    }
}
